package com.sunfeng.netty.atguigu2.nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

/**
 * @Author : 孙峰
 * @Description:
 * @Date : 2021/10/18  14:15
 */
public class GroupChatClient {

    private final String HOST="127.0.0.1";
    private final  int PORT=6667;
    private Selector selector;
    private SocketChannel socketChannel;
    private String username;

    public GroupChatClient() throws IOException {
        selector = Selector.open();
        //链接服务器
        socketChannel = SocketChannel.open(new InetSocketAddress(HOST, PORT));
        //设置非阻塞
        socketChannel.configureBlocking(false);
        //注册
        socketChannel.register(selector, SelectionKey.OP_READ);
        //获取用户名
        username = socketChannel.getLocalAddress().toString().substring(1);
        System.out.println(username + "  is ok....");
    }
    //向服务器发送消息
    public void sendInfo(String info) {
        info = username + "说:" + info;
        try {
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //从服务器端回复消息
    public void readInfo() {
        try {
            int select = selector.select();
            if (select > 0) {//判断是否有可用的通道
                //获取key集合
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                //迭代
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    if (key.isReadable()) {
                        //得到相关通道
                        SocketChannel channel = (SocketChannel) key.channel();
                        //得到一个buffer
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        //读取
                        channel.read(byteBuffer);
                        //数据转为字符串
                        String s = new String(byteBuffer.array());
                        System.out.println(s.trim());
                    }
                    iterator.remove();
                }

            } else {
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws IOException {
        GroupChatClient chatClient = new GroupChatClient();
        //读取数据
        new Thread(() -> {
            while (true) {
                chatClient.readInfo();
            }
        }).start();

        //发送数据
        Scanner sc = new Scanner(System.in);
        while (sc.hasNextLine()) {
            String s = sc.nextLine();
            chatClient.sendInfo(s);
        }
    }
}
